const router = require("koa-router")();
const controller = require("../controller/user");
const JWT = require("../utils/jwt_util");
const { SuccessModel, ErrorModel } = require("../model/resModel");

router.prefix("/user");

router.post("/register", async function (ctx, next) {
    const { username, password } = ctx.request.body;
    const data = await controller.doRegister(username, password);

    if (!data.err) {
        // 设置 session
        ctx.session.username = data.username;

        ctx.body = new SuccessModel(data, "注册成功");
    } else {
        ctx.body = new ErrorModel("注册失败");
    }
});

router.post("/login", async function (ctx, next) {
    // console.log("routes/user/login beforeHandle ctx.session",ctx.session);

    // 从request.body中拿到username, password
    const { username, password } = ctx.request.body;
    // console.log("你妹2",username, password);

    // 调用controller的login方法拿到登录结果
    const data = await controller.doLogin(username, password);
    console.log("你妹3",data);

    /* 结果无误 */
    if (data.data?.length) {
        // console.log("routes/user/login 生成后立刻校验", JWT.verify(token));
        // console.log("routes/user/login ctx.session",ctx.session);

        // 登录成功时设置一个session
        // console.log("你妹",username, password);
        const token = JWT.generate({ username, password }, "3600s");
        ctx.session.username = username;
        data.token = token;

        // 设置成功响应体
        ctx.body = new SuccessModel(data, "登录成功");
    } else {
        // 设置失败响应体
        ctx.body = new ErrorModel("登录失败");
    }
});

module.exports = router;
